﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using AudioCore.Entity;
using AudioCore.Biz;
using AudioCore.Common;
using AudioBookWS.ServiceUtil;
using AudioBook.AudioManagement.Util;

namespace AudioBook.AudioManagement.CategoryManage
{
    public partial class EditCategory : System.Web.UI.Page
    {
        #region Fields & constants

        CategoryBiz bizCategory = new CategoryBiz();
        List<CategoryEntity> lstCategory = new List<CategoryEntity>();

        #endregion Fields & constants

        #region Private methods

        private void LoadData()
        {
            CategoryEntity enCategory = LoadCurrentCategory();
            LoadParentCategory(enCategory);
        }

        private CategoryEntity LoadCurrentCategory()
        {
            int categoryID = int.Parse(hidCategoryID.Value);
            CategoryEntity enCategory = bizCategory.GetCategoryByID(categoryID);
            if (enCategory != null && enCategory.ParentID != 0)
            {
                txtCategoryName.Text = enCategory.CategoryName;
                txtDescription.Text = enCategory.Description;
                txtSortOrder.Text = enCategory.SortOrder.ToString(GUIConstants.Common.DATE_TIME_FORMAT);
                calSortOrder.Format = GUIConstants.Common.DATE_TIME_FORMAT;
                calSortOrder.SelectedDate = enCategory.SortOrder;
                chkActive.Checked = enCategory.Actived;
                imgImage.ImageUrl = string.Format(GUIConstants.WebPage.CommonPage.LoadImage, WSConstants.ContentType.Category, categoryID.ToString(), 0, 0);
            }
            else
            {
                Response.Redirect(GUIConstants.WebPage.CategoryPage.DefaultCategory);
            }
            return enCategory;
        }

        private void LoadParentCategory(CategoryEntity current)
        {
            dropParent.Items.Clear();
            List<CategoryEntity> lstCatTemp = bizCategory.GetAllCategory();
            lstCatTemp.Sort(delegate(CategoryEntity en1, CategoryEntity en2) { return en2.SortOrder.CompareTo(en1.SortOrder); });
            ProcessCategory(lstCatTemp, 0, current, string.Empty);
        }

        private void ProcessCategory(List<CategoryEntity> lstParent, int parentID, CategoryEntity current, string space)
        {
            List<CategoryEntity> lstChild = lstParent.Where(item => item.ParentID == parentID && item.CategoryID != current.CategoryID).ToList<CategoryEntity>();
            foreach (CategoryEntity item in lstChild)
            {
                item.CategoryName = space + item.CategoryName;
                ListItem dropItem = new ListItem(item.CategoryName, item.CategoryID.ToString());
                if (item.CategoryID == current.ParentID)
                {
                    dropItem.Selected = true;
                }
                dropParent.Items.Add(dropItem);
                ProcessCategory(lstParent, item.CategoryID, current, space + "---+");
            }
        }

        private bool CheckValid()
        {
            if (string.IsNullOrEmpty(txtCategoryName.Text))
            {
                valCommon.IsValid = false;
                valCommon.ErrorMessage = "The [Title] could not be empty.";
                return false;
            }

            DateTime dateValue;
            if (!DateTime.TryParseExact(txtSortOrder.Text, GUIConstants.Common.DATE_TIME_FORMAT, null, System.Globalization.DateTimeStyles.None, out dateValue))
            {
                valCommon.IsValid = false;
                valCommon.ErrorMessage = "The [Sort order] must be type of Date time.";
                return false;
            }
            return true;
        }

        private int SaveCategory()
        {
            if (CheckValid())
            {
                int categoryID = int.Parse(hidCategoryID.Value);
                CategoryEntity enCategory = bizCategory.GetCategoryByID(categoryID);
                if (enCategory == null)
                {
                    Response.Redirect(GUIConstants.WebPage.CategoryPage.DefaultCategory);
                }
                enCategory.ParentID = int.Parse(dropParent.SelectedValue);
                enCategory.CategoryName = txtCategoryName.Text;
                if (fulImage.HasFile)
                {
                    enCategory.HasImage = true;
                }
                enCategory.LastTimeUpdate = DateTime.Now;
                enCategory.Actived = chkActive.Checked;
                enCategory.Description = txtDescription.Text;
                enCategory.SortOrder = DateTime.ParseExact(txtSortOrder.Text, GUIConstants.Common.DATE_TIME_FORMAT, null, System.Globalization.DateTimeStyles.None);

                int result = bizCategory.UpdateCategory(enCategory);
                if (result > 0)
                {
                    string strImg = GlobalParam.DataFolder + Constant.CATEGORY_FOLDER + result.ToString() + Constant.IMAGE_EXTENSION;
                    fulImage.SaveAs(strImg);
                }
                else
                {
                    valCommon.IsValid = false;
                    valCommon.ErrorMessage = "Transaction error, the category is not inserted successfully.";
                }
                return result;
            }
            else
            {
                return 0;
            }
        }

        #endregion

        #region Event handlers

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int intValue;
                if (Request.QueryString[GUIConstants.Common.ID_QUERY] != null
                    && int.TryParse(Request.QueryString[GUIConstants.Common.ID_QUERY], out intValue))
                {
                    hidCategoryID.Value = intValue.ToString();
                    LoadData();
                }
                else
                {
                    Response.Redirect(GUIConstants.WebPage.CategoryPage.DefaultCategory);
                }
            }
        }

        protected void btnSaveAndClose_Click(object sender, EventArgs e)
        {
            int result = SaveCategory();
            if (result > 0)
            {
                Response.Redirect(GUIConstants.WebPage.CategoryPage.DefaultCategory);
            }
        }

        protected void btnSaveAndNew_Click(object sender, EventArgs e)
        {
            int result = SaveCategory();
            if (result > 0)
            {
                Response.Redirect(GUIConstants.WebPage.CategoryPage.AddCategoryPage);
            }
        }

        #endregion

    }
}
